package com.wangwen.wechatmp.utils;

import com.wangwen.wechatmp.model.GiftInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: wangwei
 * @Date: 2019/12/5 19:58
 *      抽奖工具类，根据奖项概率配比 计算
 *
 */


public class  DrawLotteryUtil {

    public static int drawGift(List<GiftInfo> giftList){

        if(null != giftList && giftList.size()>0){
            List<Double> orgProbList = new ArrayList<Double>(giftList.size());
            for(GiftInfo giftInfo :giftList){
                //按顺序将概率添加到集合中
                orgProbList.add(giftInfo.getProb());
            }

            return draw(orgProbList);

        }
        return -1;
    }

    public static int draw(List<Double> giftProbList) {

        List<Double> sortRateList = new ArrayList<Double>();

        // 计算概率总和
        Double sumRate = 0D;
        for (Double prob : giftProbList) {
            sumRate += prob;
        }

        if (sumRate != 0) {
            double rate = 0D;   //概率所占比例
            for (Double prob : giftProbList) {
                rate += prob;
                // 构建一个比例区段组成的集合(避免概率和不为1)
                sortRateList.add(rate / sumRate);
            }

            // 随机生成一个随机数，并排序
            double random = Math.random();
            sortRateList.add(random);
            Collections.sort(sortRateList);

            // 返回该随机数在比例集合中的索引
            return sortRateList.indexOf(random);
        }


        return -1;
    }

//    public static void main(String[] args) {
//        GiftInfo iphone = new GiftInfo();
//        iphone.setId(101);
//        iphone.setName("苹果手机");
//        iphone.setProb(0.01D);
//
//        GiftInfo thanks = new GiftInfo();
//        thanks.setId(102);
//        thanks.setName("再接再厉");
//        thanks.setProb(0.2D);
//
//        GiftInfo vip = new GiftInfo();
//        vip.setId(103);
//        vip.setName("优酷会员");
//        vip.setProb(0.2D);
//
//        GiftInfo hah = new GiftInfo();
//        hah.setId(104);
//        hah.setName("微笑");
//        hah.setProb(0.5D);
//
//        List<GiftInfo> list = new ArrayList<GiftInfo>();
//        list.add(vip);
//        list.add(thanks);
//        list.add(iphone);
//        list.add(hah);
//
//        int index = drawGift(list);
//        System.out.println(list.get(index));
//
//    }


}
